<?php

declare(strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */
namespace App\Service;

use App\Constants\Constants;

use AlibabaCloud\Client\AlibabaCloud;
use App\Exception\CustomException;

/**
 * 短信服务
 *
 * @author 刘兴永(aile8880@qq.com)
 * @package App\Controller
 */
class SMSService extends Service
{
    /**
     * 发送短信
     *
     * @param string $phone
     * @param string $templateCode
     * @param array $templateParam
     */
    public function sendCode(string $phone, string $templateCode, array $templateParam)
    {
        $record = $this->redis->get(Constants::CODE_REDIS_PREFIX . $phone);
        $record = !$record ?: json_decode($record, true);

        // 判断短信间隔时间
        if ($record && time() < $record['time'] + Constants::CODE_LIMIT_SECOND) {
            $this->error('SMS.CODE_SEND_LIMIT');
        }

        // 不需要返回值的请求放到协程去执行，前台用户不需要同步等待；因为验证码可以始终反馈给用户发送成功，所以接口始终直接返回200状态即可
        // go(function() use ($phone, $templateCode, $templateParam) {
            try {
                // 获取配置
                $accessKeyId = gConfig('ali_accessKeyId');
                $accessSecret = gConfig('ali_accessSecret');
                $signName = gConfig('ali_signName');

                // 载入阿里云配置
                AlibabaCloud::accessKeyClient($accessKeyId, $accessSecret)->regionId('cn-hangzhou')->asDefaultClient();

                $result = AlibabaCloud::rpc()
                    ->product('Dysmsapi')
                    ->version('2017-05-25')
                    ->action('SendSms')
                    ->method('POST')
                    ->host('dysmsapi.aliyuncs.com')
                    ->options([
                        'query' => [
                            'RegionId' => 'cn-hangzhou',
                            'PhoneNumbers' => $phone,
                            'SignName' => $signName,
                            'TemplateCode' => $templateCode,
                            'TemplateParam' => json_encode($templateParam)
                        ]
                    ])
                    ->request();

                $result = $result->toArray();
                $this->logger('sms')->error(json_encode($result));

                if ('OK' !== $result['Code']) {
                    // TODO 开发阶段在控制台打印验证码
                    var_dump('验证码debug: ' . $templateParam['code']);
                     //throw new CustomException($result['Message']);
                }

                $this->redis->set(Constants::CODE_REDIS_PREFIX . $phone, json_encode([
                    'code' => $templateParam['code'],
                    'time' => time()
                ]), Constants::CODE_TIMEOUT);
            }
            catch (CustomException $e) {
                $this->logger('sms')->error($e->getMessage());
                // 可以放置其它触发器，比如发送邮件通知运维
            }
        // });
    }
}